/*
 * @Author: 13177709051 3506463075@qq.com
 * @Date: 2024-12-20 21:17:06
 * @LastEditors: 13177709051 3506463075@qq.com
 * @LastEditTime: 2024-12-20 21:30:55
 * @FilePath: /linux39/自旋锁伪代码实现.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <stdio.h>
#include <stdatomic.h>
#include <pthread.h>
#include <unistd.h>
// 使用原子标志来模拟自旋锁
atomic_flag spinlock = ATOMIC_FLAG_INIT; // ATOMIC_FLAG_INIT 是0
// 尝试获取锁
void spinlock_lock()
{
    while (atomic_flag_test_and_set(&spinlock))
    {
        // 如果锁被占用，则忙等待
    }
}
// 释放锁
void spinlock_unlock()
{
    atomic_flag_clear(&spinlock);
}

typedef _Atomic struct
{
#if __GCC_ATOMIC_TEST_AND_SET_TRUEVAL == 1
    _Bool __val;
#else
    unsigned char __val;
#endif
} atomic_flag;


#include <pthread.h>
int pthread_spin_lock(pthread_spinlock_t *lock);
int pthread_spin_trylock(pthread_spinlock_t *lock);
int pthread_spin_unlock(pthread_spinlock_t *lock);
int pthread_spin_init(pthread_spinlock_t *lock, int pshared);
int pthread_spin_destroy(pthread_spinlock_t *lock);